package com.vvlive.caibao.smartcity.utils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.View;

import com.vvlive.caibao.smartcity.app.SmartCityApp;
import com.vvlive.caibao.smartcity.bean.Friend;
import com.vvlive.caibao.smartcity.bean.User;
import com.vvlive.caibao.smartcity.message.ContactNotification;
import com.vvlive.caibao.smartcity.message.GroupNotification;

import io.rong.imkit.RongIM;
import io.rong.imkit.model.UIConversation;
import io.rong.imlib.AnnotationNotFoundException;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.RongIMClient.ConnectCallback;
import io.rong.imlib.RongIMClient.SendMessageCallback;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.imlib.model.UserInfo;


/**
 * RongUtil.getInstanse().xxx();
 *
 * @author zhj
 *         融云工具类
 */
public class RongUtil {

    private static final String GROUP_PORTRAIT =
            "http://b.hiphotos.baidu.com/image/w%3D310/sign=12445d59fadcd100cd9cfe20428a47be/c995d143ad4bd1135a73406658afa40f4bfb0523.jpg";

    private static RongUtil rongUtil;

    /**
     * Prevent this class from being instanced.
     */
    private RongUtil() {
    }

    public static RongUtil getInstance() {
        if (rongUtil == null) {
            rongUtil = new RongUtil();
        }
        return rongUtil;
    }

    /**
     * 初始化融云服务
     *
     * @param context
     */
    public void init(Context context) {
        RongIM.init(context);
        setUserInfo();
        log("融云服务初始化成功");
    }

    /**
     * 1. 连接融云服务器
     * 2. 注册自定义的消息类型（好友请求和群组邀请）
     * 3. 设置融云监听器
     *
     * @param token    token
     * @param callback 连接回调
     * @throws Exception
     */
    public void connect(String token, ConnectCallback callback) throws Exception {
        // 连接融云的服务器
        RongIM.connect(token, callback);
        // 注册自定义的消息类型
        registerCustomMessageType();
        // 设置监听器
        setRongListeners();
    }

    /**
     * 设置融云的监听器
     */
    private void setRongListeners() {
        // 接收消息监听
        RongIM.setOnReceiveMessageListener(new RongReceiveMessageListener());
        // 会话列表行为监听
        RongIM.setConversationListBehaviorListener(new RongConversationListBehaviorListener());
        // 会话消息行为监听
        RongIM.setConversationBehaviorListener(new RongConversationBehaviorListener());
        // 融云连接状态监听
        RongIMClient.setConnectionStatusListener(new RongConnectionStatusListener());

    }

    /**
     * 融云接收消息监听
     */
    private final class RongReceiveMessageListener implements RongIMClient.OnReceiveMessageListener {
        public boolean onReceived(Message message, int left) {    // message: 接收到的消息， left: 未读消息数
            dealMessageReceived(message);    // 调用方法处理接收到的消息
            return false;    // false: 系统处理, true: 自己处理
        }
    }

    /**
     * 融云会话列表行为监听（点击，长按）
     */
    private final class RongConversationListBehaviorListener implements RongIM.ConversationListBehaviorListener {
        public boolean onConversationLongClick(Context context, View view, UIConversation uiConversation) {
            log("列表被长按");
            return false;    // false: 系统处理长按事件， true: 自己处理列表的长按事件
        }

        public boolean onConversationClick(Context context, View view, UIConversation uiConversation) {
            log("列表被点击");
            return false;    // false: 系统处理列表的点击事件， true: 自己处理列表的点击事件
        }
    }

    /**
     * 融云服务连接状态监听
     */
    private final class RongConnectionStatusListener implements RongIMClient.ConnectionStatusListener {
        public void onChanged(ConnectionStatus connectionStatus) {
            log("连接状态发生改变 [ Message >> " + connectionStatus.getMessage() + ", Name >> " + connectionStatus.name() + " ]");
            /*
			 * DISCONNECTED(2, "Disconnected"),
             * CONNECTED(0, "Connect Success."),
             * CONNECTING(1, "Connecting"),
             * NETWORK_UNAVAILABLE(-1, "Network is unavailable."),
             * KICKED_OFFLINE_BY_OTHER_CLIENT(6, "Login on the other device, and be kicked offline.");
			 */
            switch (connectionStatus.getValue()) {
                case 2:
                    // Disconnected	【断开连接】
                    break;
                case 0:
                    // Connect Success	【连接成功】
                    break;
                case 1:
                    // Connecting	【正在连接】
                    break;
                case -1:
                    // Network is unavailable	【网络不可用】
                    break;
                case 6:
                    // Login on the other device, and be kicked offline	【当前用户在其他设备登录，该用户已经下线】
                    break;
            }
        }
    }

    private final class RongConversationBehaviorListener implements RongIM.ConversationBehaviorListener {

        public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {
            if (userInfo != null)
                log("不小心点击了头像 >> Name =  " + userInfo.getName() + ", PortraitUri = " + userInfo.getPortraitUri());
            return false;
        }

        public boolean onUserPortraitLongClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {
            if (userInfo != null)
                log("不小心长按了头像");
            return false;
        }

        public boolean onMessageClick(Context context, View view, Message message) {
            log("不小心点击了消息");
            return false;
        }

        public boolean onMessageLongClick(Context context, View view, Message message) {
            log("不消息长按了消息");
            return false;
        }
    }

    /**
     * 注册自定义的消息类型
     *
     * @throws AnnotationNotFoundException
     */
    private void registerCustomMessageType() throws AnnotationNotFoundException {
        // 注册好友请求消息类型
        RongIM.registerMessageType(ContactNotification.class);
        // 注册群组请求消息类型
        RongIM.registerMessageType(GroupNotification.class);
    }

    /**
     * 设置用户信息提供者
     * (接收到消息时调用， 根据此时信息发送者的Id获得其信息)
     */
    public void setUserInfo() {
        RongIM.setUserInfoProvider(new MyUserInfoProvider(), false);
    }

    /**
     * 用户信息提供者
     */
    private class MyUserInfoProvider implements RongIM.UserInfoProvider {
        public UserInfo getUserInfo(String userId) {
            return getTargetUserById(userId);
        }
    }

    /**
     * 根据userId获得用户信息
     *
     * @param userId
     * @return
     */
    public UserInfo getTargetUserById(String userId) {

        if (SmartCityApp.friends != null) {
            for (Friend friend : SmartCityApp.friends)
                if (userId.equals(friend.getUserId()))
                    return transformFriend(friend);
        }

        if (SmartCityApp.currentUser != null)
            return transformUser(SmartCityApp.currentUser);

        return null;
    }

    /**
     * 设置群组信息提供者
     * (接收消息时调用， 根据此时接收信息的群组的Id获取该群组的信息)
     */
    public void setGroupsInfo() {
        log("设置群组信息提供者");
//		RongIM.setGroupInfoProvider((String groupId) -> getTargetGroupById(groupId), false);
        RongIM.setGroupInfoProvider(new MyGroupInfoProvider(), false);
    }

    /**
     * 群组信息提供者
     */
    private class MyGroupInfoProvider implements RongIM.GroupInfoProvider {
        public Group getGroupInfo(String groupId) {
            return getTargetGroupById(groupId);
        }
    }


    /**
     * 根据群组Id获得群组信息（Unfinished）
     *
     * @param groupId
     * @return
     */
    public Group getTargetGroupById(String groupId) {
        return new Group("54918579d8", "4cc", Uri.parse(GROUP_PORTRAIT));
    }

    /**
     * 发送好友通知 （默认是好友请求）
     *
     * @param targetId 对方的ID
     * @param message  通知信息
     */
    public void sendFriendNotification(String targetId, String message, SendMessageCallback sendListener) {

        log("sendFriendNotification >> " + message);
        sendFriendNotification(targetId, message, ContactNotification.REQUEST, sendListener);

    }

    /**
     * 发送好友通知
     *
     * @param targetId 对方ID
     * @param message  通知消息
     * @param tag      通知类型
     */
    public void sendFriendNotification(String targetId, String message, int tag, SendMessageCallback sendListener) {

        ContactNotification contactNotification = new ContactNotification(message, tag);
        sendNotification(targetId, contactNotification, message, sendListener);

    }

    /**
     * 发送群组通知（默认是群组邀请）
     *
     * @param targetUserId 接收者的ID
     * @param groupId      群组Id
     * @param message      通知信息
     */
    public void sendGroupNotification(String targetUserId, String groupId, String message, SendMessageCallback sendListener) {

        sendGroupNotification(targetUserId, groupId, message, GroupNotification.INVITATION, sendListener);

    }

    /**
     * 发送群组通知
     *
     * @param groupId 群组ID
     * @param message 通知信息
     * @param tag     通知类型
     */
    public void sendGroupNotification(String targetUserId, String groupId, String message, int tag, SendMessageCallback sendListener) {

        GroupNotification groupNotification = new GroupNotification(groupId, message, tag);
        sendNotification(targetUserId, groupNotification, message, sendListener);

    }

    /**
     * 发送请求
     *
     * @param targetId    目标ID
     * @param content     请求内容
     * @param pushContent 推送内容
     */
    public void sendNotification(String targetId, MessageContent content, String pushContent, SendMessageCallback sendMessageCallback) {

        RongIMClient.getInstance().sendMessage(Conversation.ConversationType.SYSTEM, targetId, content, pushContent, sendMessageCallback);

    }

    /**
     * 处理接收到的消息
     *
     * @param message
     */
    private void dealMessageReceived(Message message) {

        MessageContent msgContent = message.getContent();

        log("MESSAGE RECEIVED FOR JSON : " + new String(msgContent.encode()));
        message.getSenderUserId();

        if (msgContent instanceof ContactNotification) {

            ContactNotification contact = (ContactNotification) msgContent;

            if (contact.getTag() == 1) {
                // 接受了好友请求
                NotificationUtil.send(SmartCityApp.context, "好友请求回复", "对方接受了你的好友请求", contact.getMessage()/*xxx接收了你的好友请求*/, new Intent());
            } else if (contact.getTag() == -1) {
                // 拒绝了好友请求
                NotificationUtil.send(SmartCityApp.context, "好友请求回复", "对方拒绝了你的好友请求", contact.getMessage()/*xxx拒绝了你的好友请求*/, new Intent());
            } else if (contact.getTag() == 0) {
//				Intent intent = new Intent(App.context, ReceiveRequestActivity.class);
//				intent.putExtra("id", message.getSenderUserId());
//				intent.putExtra("message", contact.getMessage());
//				NotificationUtil.send(App.context, "你有一条好友请求", "接收到一条来自" +message.getSenderUserId()+ "的好友请求消息", "附加信息：" +contact.getMessage(), intent);
            }


        } else if (msgContent instanceof GroupNotification) {

            GroupNotification group = (GroupNotification) msgContent;
            log("接收到一条来自" + message.getSenderUserId() + "的群组邀请消息");
            log("附加信息：" + group.getMessage());
            log("消息接收结束");

            switch (group.getTag()) {
                case GroupNotification.INVITATION:
                    // 接收到群组邀请通知之后，跳转到处理该请求的页面
                    break;
                case GroupNotification.INVITE_ACCEPTED:

                    break;
                case GroupNotification.INVITE_APPLY:
                    // 接收到群组申请加入的消息之后，跳转到处理该请求的页面
                    NotificationUtil.send(SmartCityApp.context, "群组消息", "收到一条群组消息", group.getMessage()/* xxx申请加入群组xxx */, new Intent());
                    break;
                case GroupNotification.KICKED_OUT:
                    // 接收到自己被踢出群组的推送消息之后，更新服务器端的Groups表(members)和Friends表(groups)
                    NotificationUtil.send(SmartCityApp.context, "群组消息", "收到一条群组信息", group.getMessage()/* 你已经被踢出群组xxx */, new Intent());
                    break;
            }
        }

    }

    /**
     * 把User转换成融云的UserInfo对象
     *
     * @param user
     * @return
     */
    private UserInfo transformUser(User user) {
        return new UserInfo(user.getObjectId(), user.getUsername(), Uri.parse(user.getPortraitUri()));

    }

    /**
     * 把Friend转换成融云的UserInfo对象
     *
     * @param friend
     * @return
     */
    private UserInfo transformFriend(Friend friend) {
        return new UserInfo(friend.getUserId(), friend.getNickName(), Uri.parse(friend.getPortraitUri()));
    }

    /**
     * Log
     *
     * @param msg
     */
    private void log(Object msg) {
        Log.i(SmartCityApp.Constants.TAG, msg.toString());
    }
    //I/Smart
}
